/* 
 * Copyright (C) 2013 National University of Defense Technology(NUDT) & Kylin Ltd. 
 * 
 * Authors: 
 *  Kobe Lee   kobe24_lixiang@126.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <syslog.h>
#include "log.h"
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>


#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <time.h>
#include <stdarg.h>

#define PROG_NAME "activation"
#define LOG_FILE "/var/log/activation.log"
#define MAX_SIZE 1024

/* Return the date and time as a string.  Some callers tweak returned buf. */
char *timestring(time_t t)
{
        static char TimeBuf[200];
        struct tm tm;
       	localtime_r(&t, &tm);
        char *p;

        strftime(TimeBuf, sizeof TimeBuf - 1, "%Y-%m-%d %H:%M:%S", &tm);

        if ((p = strchr(TimeBuf, '\n')) != NULL)
                *p = '\0';

        return TimeBuf;
}

//日志记录
int log_msg( const char *format, ... )
{
    va_list args;
        int fd, len;
	int ptr;
        char buffer[MAX_SIZE];

        fd = open( LOG_FILE, O_WRONLY | O_APPEND | O_CREAT, 0644 );
        if( fd < 0 ){
                perror("Failed to open fifo file");
                return -1;
        }
	sprintf(buffer, "%s %s: ",
		timestring(time(NULL)), PROG_NAME);
	ptr = strlen(buffer); 
        va_start( args, format );
        len=vsnprintf( buffer+ptr, MAX_SIZE-ptr-1, format, args );
        va_end( args );
	len+=ptr;
	if(buffer[len-1] != '\n'){
		buffer[len++] = '\n';	
	}
        if( write( fd, buffer, len ) < 0 ){
                perror("Failed to write fifo file");
        }

        close( fd );
        return 0;
}

